package com.taotao.content.service;


import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.content.jedis.JedisClientPool;
import com.taotao.mapper.TbContentMapper;
import com.taotao.pojo.TbContent;
import com.taotao.pojo.TbContentExample;
import com.taotao.pojo.TbContentExample.Criteria;
import com.taotao.utils.JsonUtils;

@Service
public class ContentServiceImpl implements ContentService {
	
	@Autowired 
	private TbContentMapper contentMapper;
	@Autowired
	private JedisClientPool clientPool;

	@Override
	public TaotaoResult addContent(TbContent tbContent) {
		tbContent.setCreated(new Date());
		tbContent.setUpdated(new Date());
		
		
		clientPool.hdel("INDEX_CONTENT", tbContent.getCategoryId().toString());
		
		contentMapper.insert(tbContent);
		
		return TaotaoResult.ok();
	}

	@Override
	public List<TbContent> showAd(long cid) {
		try{
			String string = clientPool.hget("INDEX_CONTENT",cid+"");
			if(StringUtils.isNotEmpty(string)){
				List<TbContent> list = JsonUtils.jsonToList(string, TbContent.class);
				return list;
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
		TbContentExample example=new TbContentExample();
		Criteria criteria=example.createCriteria();
		
		criteria.andCategoryIdEqualTo(cid);
		
		List<TbContent> list=contentMapper.selectByExample(example);
		
		try{
			clientPool.hset("INDEX_CONTENT",cid+"", JsonUtils.objectToJson(list));
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return list;
	}

}
